#include "StdAfx.h"
#include "CalcStartParam.h"

auto_ptr<CCalcStartParam>	CCalcStartParam::s_StaticParam;
CCriticalSection			CCalcStartParam::s_cs;
int							CCalcStartParam::s_count = 0;

CCalcStartParam::CCalcStartParam(LPCTSTR stzFileName)
{
	using namespace boost::property_tree;
	ptree pt;

	try
	{
		xml_parser::read_xml(stzFileName, pt);
		m_nStepCount = pt.get("StartCalc.Step", 10);
		m_nUseKm = pt.get("StartCalc.UseKm", 1);
		m_nSameRange = pt.get("StartCalc.SameRange", 1);
		m_nUseSelectedTime = pt.get("StartCalc.UseSelectedTime", 1);
	}
	catch(xml_parser_error &e)
	{
		throw CCustomException("line %d file %s:\n%s", e.line(), e.filename().c_str(), e.message().c_str());
	}
	catch (const ptree_bad_data& error)
	{
		throw CCustomException("ptree_bad_data: %s", error.what());
	}
	catch (const ptree_bad_path& error)
	{
		throw CCustomException("ptree_bad_path: %s", error.what());
	}
	catch(...)
	{
		throw CCustomException("Unknown error");
	}
	++s_count;
}

CCalcStartParam::CCalcStartParam(void)
: m_nStepCount(10)
, m_nUseKm(1)
, m_nSameRange(1)
, m_nUseSelectedTime(1)
{
	CAutoCriticalSection acs(s_cs);
	if(s_StaticParam.get() == NULL)
	{
		LPCTSTR stzConfigFile = GetFileName();
		if(stzConfigFile == NULL || stzConfigFile[0] == 0)
			throw CCustomException(_T("CalcStartParam::CalcStartParam: empty config file name"));

		s_StaticParam = auto_ptr<CCalcStartParam>(new CCalcStartParam(stzConfigFile));
	}
	*this = *s_StaticParam;
	++s_count;
}

CCalcStartParam::~CCalcStartParam(void)
{
	--s_count;
	if(s_count == 1) // only static still destroy it
	{
		s_StaticParam.reset();
	}

	if(s_StaticParam.get() == this) // this is last? should store settings
	{
		CStdString strError;
		using namespace boost::property_tree;
		ptree pt;

		try
		{
			xml_parser::read_xml(GetFileName(), pt);

			pt.put("StartCalc.Step", m_nStepCount);
			pt.put("StartCalc.UseKm", m_nUseKm);
			pt.put("StartCalc.SameRange", m_nSameRange);
			pt.put("StartCalc.UseSelectedTime", m_nUseSelectedTime);

			xml_parser::write_xml(GetFileName(), pt);
		}
		catch(xml_parser_error &e)
		{
			throw CCustomException("line %d file %s:\n%s", e.line(), e.filename().c_str(), e.message().c_str());
		}
		catch(...)
		{
			strError = _T("Unknown error");
		}

		if(strError.length())
		{
			strError.Format(_T("Error storing rada param: %s"), strError.c_str());
			AfxMessageBox(strError);
		}
	}
}

bool CCalcStartParam::Update()
{
	*s_StaticParam = *this;
	return true;
}